package com.baiyun.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Slf4j
@Component
@RequiredArgsConstructor
public class JwtUtils {
    private final JwtUtilsProperties jwtUtilsProperties;


    public String createJWT(Map<String, Object> userInfo) {
        long vildTime = jwtUtilsProperties.getVildTime();
        String secretKey = jwtUtilsProperties.getSecretKey();
        //设置过期时间
        Date expirationTime = new Date(System.currentTimeMillis() + vildTime);
        //生成token
        String token = Jwts.builder()
                .setClaims(userInfo)
                .signWith(SignatureAlgorithm.HS256, secretKey)
                .setExpiration(expirationTime)
                .compact();

        log.info("token:{}", token);
        return token;
    }


    public Claims parseJWT(String token) {
        String secretKey = jwtUtilsProperties.getSecretKey();
        Claims claims = Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(token)
                .getBody();
        log.info("用户信息:{}", claims);
        return claims;
    }
}
